<script lang="ts" setup>
import { createRuleAPI, delRuleAPI, getRuleDetailAPI, getRuleListAPI, updateRuleAPI } from '@/apis/card';
import type { CreateRuleParams, DurationRuleParams, PartitionRuleParams, Rule, RuleListParams, TurnRuleParams } from '@/types/card';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';
import { utils, writeFileXLSX } from 'xlsx'
// 导出Excel
const exportToExcel = ()=>{
  // 1. 创建工作簿 (xlsx文件)  
  const workbook = utils.book_new()
  // 2. 创建工作表 (表格)
  const worksheet = utils.json_to_sheet(ruleList.value.map((item, index) => ({
    ...item,
    id: index + 1, // 把 id 覆盖成序号
    chargeType: chargeTypeMap.get(item.chargeType) // 把 chargeType 覆盖成中文
  })))
  // 3. 往工作簿中添加表格 (工作簿, 表格, 表格名)
  utils.book_append_sheet(workbook, worksheet, '计费规则')
  // 4. 覆盖默认标题 (表格, 二维数组, 标题位置)
  utils.sheet_add_aoa(
    worksheet,
    // aoa -> array of arrays -> 二维数组
    [
      ['序号', '计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上限(元)', '计费方式', '计费规则'],
    ],
    { origin: 'A1' }
  )
  // 4. 导出(下载) xlsx 文件
  writeFileXLSX(workbook, '停车计费规则.xlsx')
}
const ruleList = ref<Rule[]>([])
const params = ref<RuleListParams>({
  page: 1,
  pageSize: 10
})
const total = ref(0)

// 获取计费规则列表
const getRuleList = async () => {
  const res = await getRuleListAPI(params.value)
  ruleList.value = res.data.rows
  total.value = res.data.total
}
getRuleList()
// 计费规则
const chargeTypeMap = new Map<Rule['chargeType'], string>([
  // [key, value] 键值对 
  ['duration', '时长收费'],
  ['turn', '按次收费'],
  ['partition', '分段消费']
]);
// 删除计费规则
const onDel = async(id: number) => {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    await delRuleAPI(id)
    ElMessage.success('删除成功')
    getRuleList()
  }).catch(() => {})
}

// 弹窗部分
const dialogVisible = ref(false)
const submitLoading = ref(false)
// 打开弹窗
const onOpen = () => {
  dialogVisible.value = true
}
// 关闭弹窗
const onClose = () => {
  dialogVisible.value = false
  baseForm.value = baseFormInit()
  durationForm.value = durationFormInit()
  turnForm.value = { turnPrice: undefined }
  partitionForm.value = partitionFormInit()
  // 重置表单校验
  baseFormRef.value?.resetFields()
  durationFormRef.value?.resetFields()
  turnFormRef.value?.resetFields()
  partitionFormRef.value?.resetFields()

}

const onEdit = async (ids: number) => {
  dialogVisible.value = true
  const res = await getRuleDetailAPI(ids)
  console.log('detail',res)
  const { id,ruleName,ruleNumber,chargeType,chargeCeiling,freeDuration,durationPrice,durationTime,durationType,turnPrice,partitionFramePrice,partitionFrameTime,partitionIncreasePrice,partitionIncreaseTime } = res.data
  baseForm.value = {
    id,
    ruleName,
    ruleNumber,
    chargeType,
    freeDuration,
    chargeCeiling
  }
  if(chargeType === 'duration'){
    durationForm.value = {
      durationPrice,
      durationTime,
      durationType
    }
  }else if (chargeType === 'turn') {
    turnForm.value = {
      turnPrice
    }
  }else if (chargeType === 'partition') {
    partitionForm.value = {
      partitionFramePrice,
      partitionFrameTime,
     partitionIncreasePrice,
     partitionIncreaseTime
    }
  }

}

// 提交表单
const onSubmit = async () => {
  try {
    submitLoading.value = true
    await baseFormRef.value?.validate()

    if(baseForm.value.id){

      if(baseForm.value.chargeType === 'duration'){
        await durationFormRef.value?.validate()
        await updateRuleAPI({
          ...baseForm.value,
          ...durationForm.value
        })
        
      }else if (baseForm.value.chargeType === 'turn') {
        await turnFormRef.value?.validate()
        await updateRuleAPI({
          ...baseForm.value,
          ...turnForm.value
        })
      }else if(baseForm.value.chargeType === 'partition'){
        await partitionFormRef.value?.validate()
        await updateRuleAPI({
          ...baseForm.value,
          ...partitionForm.value
        })
      }
      ElMessage.success('修改成功')

    }else{
      // 判断收费类型
    if(baseForm.value.chargeType === 'duration'){
      await durationFormRef.value?.validate()
      await createRuleAPI({
        ...baseForm.value,
        ...durationForm.value
      })
      
    }else if (baseForm.value.chargeType === 'turn') {
      await turnFormRef.value?.validate()
      await createRuleAPI({
        ...baseForm.value,
        ...turnForm.value
      })
     
    }else if (baseForm.value.chargeType === 'partition') {
      await partitionFormRef.value?.validate()
      await createRuleAPI({
        ...baseForm.value,
        ...partitionForm.value
      })
      
    }
    ElMessage.success('添加成功')

    }

    getRuleList()
    onClose()
    submitLoading.value = false
  } catch {
    submitLoading.value = false
  }
}

// baseFormInit
const baseFormInit = () => {
  return {
  ruleName: '',
  ruleNumber: '',
  chargeType: 'duration' as 'duration' | 'turn' | 'partition',
  freeDuration: undefined,
  chargeCeiling: undefined,
}
}
const baseFormRef = ref<FormInstance>()
// 添加表单信息
const baseForm = ref<CreateRuleParams>(baseFormInit())
const baseFormRules = ref<FormRules<CreateRuleParams>>({
  ruleName: [
    { required: true, message: '请输入计费规则名称', trigger: 'blur' },
  ],
  ruleNumber: [
    { required: true, message: '请输入计费规则编号', trigger: 'blur' },
  ],
  chargeType: [
    { required: true, message: '请选择计费方式', trigger: 'change' },
  ],
})
// durationFormInit
const durationFormInit = () => {
  return {
    durationPrice: undefined,
    durationTime: undefined,
    durationType: 'minute' as 'minute' | 'hour'
  }
}
const durationFormRef = ref<FormInstance>()
// 时长收费表单
const durationForm = ref<DurationRuleParams>(durationFormInit())
const durationFormRules = ref<FormRules<DurationRuleParams>>({
  durationPrice: [
    { required: true, message: '请输入时长收费价格', trigger: 'blur' },
  ],
  durationTime: [
    { required: true, message: '请输入时长收费时间', trigger: 'blur' },
  ],
  durationType: [
    { required: true, message: '请选择时长收费单位', trigger: 'change' },
  ]
})

// 按次收费表单
const turnFormRef = ref<FormInstance>()
const turnForm = ref<TurnRuleParams>({
  turnPrice: undefined
})
const turnFormRules = ref<FormRules<TurnRuleParams>>({
  turnPrice: [
    { required: true, message: '请输入按次收费价格', trigger: 'blur' },
  ]
})
// 分段收费表单
const partitionFormRef = ref<FormInstance>()
const partitionFormInit = () => {
  return {
    partitionFramePrice: undefined,
    partitionFrameTime: undefined,
    partitionIncreasePrice: undefined,
    partitionIncreaseTime: undefined,
  }
}
const partitionForm = ref<PartitionRuleParams>(partitionFormInit())
const partitionFormRules = ref<FormRules<PartitionRuleParams>>({
  partitionFramePrice: [
    { required: true, message: '请输入分段收费:段内费用', trigger: 'blur' },
  ],
  partitionFrameTime: [
    { required: true, message: '请输入分段收费:段内时间', trigger: 'blur' },
  ],
  partitionIncreasePrice:[
    { required: true, message: '请输入分段收费:超出范围收费价钱', trigger: 'blur' },
  ],
  partitionIncreaseTime: [
    { required: true, message: '请输入分段收费:超出时间', trigger: 'blur' },
  ]
})

</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="onOpen">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{ row }">
            {{ chargeTypeMap.get(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" width="320" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="onEdit(row.id)">编辑</el-button>
            <el-button size="small" type="primary" link @click="onDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container" style="display: flex;justify-self: end;">
      <el-pagination 
      layout="total, prev, pager, next, sizes, jumper"
      :page-sizes="[2, 5, 10, 20, 100]"
      :total="total" 
      v-model:current-page="params.page" 
      v-model:page-size="params.pageSize"
      @change="getRuleList()"
      />
    </div>
    <el-dialog v-model="dialogVisible" width="600px" :title="baseForm.id ? '编辑计费规则' :'添加计费规则'" @close="onClose">

      <div class="form-container">
        {{ baseForm }}
        <el-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber" >
            <el-input v-model="baseForm.ruleNumber" placeholder="请输入计费规则编号" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="baseForm.ruleName" placeholder="请输入计费规则名称" />
          </el-form-item>
          <el-form-item label="计费方式(全天收费)" prop="chargeType">
              <el-radio-group v-model="baseForm.chargeType" >
                <el-radio border label="duration">时长收费</el-radio>
                <el-radio border label="turn">按次收费</el-radio>
                <el-radio border label="partition">分段收费</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-form-item label="免费时长" prop="">
              <el-input type="number" :min="0" style="width: 180px;" v-model="baseForm.freeDuration" >
                <template #append>分钟</template> 
              </el-input>
            </el-form-item>
            <el-form-item label="收费上限" prop="" style="width: 180px;margin-left: 20px;">
              <el-input type="number" :min="0" v-model="baseForm.chargeCeiling">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-container" v-if="baseForm.chargeType === 'duration'">
        <el-form ref="durationFormRef" :model="durationForm" :rules="durationFormRules" label-position="top" >
          <el-form-item label="计费规则">
            <el-form-item prop="durationTime">
             <el-input placeholder="请输入" v-model="durationForm.durationTime" style="width: 120px;">
              <template #prepend>每</template>
             </el-input>
            </el-form-item>
            <el-form-item prop="durationType">
              <el-select v-model="durationForm.durationType" style="width: 120px;margin-left: 10px;"  placeholder="请选择" clearable>
                <el-option value="minute" label="分钟"></el-option>
                <el-option value="hour" label="小时"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="durationPrice">
              <el-input v-model="durationForm.durationPrice" style="width: 120px;margin-left: 10px;" placeholder="请输入" >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
        {{ durationForm }}
      </div>
      <div class="form-container" v-if="baseForm.chargeType === 'turn'">
        <el-form ref="turnFormRef" :model="turnForm" :rules="turnFormRules" label-position="top" >
          <el-form-item label="计费规则" prop="turnPrice">
              <el-input v-model="turnForm.turnPrice"  placeholder="请输入" >
                <template #prepend>每次</template>
                <template #append>元</template>
              </el-input>
          </el-form-item>
        </el-form>
        {{ turnForm }}
      </div>
      <div class="form-container" v-if="baseForm.chargeType === 'partition'">
        <el-form ref="partitionFormRef" :model="partitionForm" :rules="partitionFormRules" label-position="top" >
          <el-form-item label="计费规则">
            <el-form-item prop="partitionFrameTime">
              <el-input placeholder="请输入" v-model="partitionForm.partitionFrameTime" style="width: 200px;">
                <template #append>小时内</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="partitionFramePrice">
              <el-input v-model="partitionForm.partitionFramePrice" style="width: 200px;" placeholder="请输入" >
                <template #prepend>每小时</template>
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item  prop="">
            <el-form-item prop="partitionIncreaseTime">
              <el-input placeholder="请输入" v-model="partitionForm.partitionIncreaseTime" style="width: 200px;">
                <template #prepend>每增加</template>
                <template #append>小时</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="partitionIncreasePrice">
              <el-input v-model="partitionForm.partitionIncreasePrice" style="width: 200px;" placeholder="请输入" >
                <template #prepend>增加</template>
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-form-item>
        </el-form>
        {{ partitionForm }}
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.rules .el-form-item {
  padding: 0 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>